package com.xxm.thoughtworksdemo

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.appbar.AppBarLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.xxm.thoughtworksdemo.databinding.ActivityMainBinding
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.functions.Consumer
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import kotlin.math.abs


class MainActivity : AppCompatActivity() {
    val adapter = TweeAdapter(this)
    val twees = ArrayList<TweeBean>()

    var page = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        immersionBar {
        }

        val bind = ActivityMainBinding.inflate(layoutInflater)
        setContentView(bind.root)


        bind.refreshLayout.setOnRefreshListener {
            page=0
            adapter.setList(page(page))
            bind.refreshLayout.isRefreshing=false
        }

        adapter.mOnLoadMoreListener=object : TweeAdapter.OnLoadMoreListener{
            override fun onLoadMore() {
                Single.timer(1, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(Consumer {
                        var list = page(++page)
                        if(list.isEmpty()){
                            adapter.mLoadMoreEnable=false
                        }else{
                            adapter.addList(list)
                        }
                    })
            }
        }

        bind.appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            val color = Color.argb(200, 0, 0, 0)
            bind.collapsingToolbar.setCollapsedTitleTextColor(color)
            if (abs(verticalOffset) >= appBarLayout.totalScrollRange) { // 折叠状态
                bind.collapsingToolbar.title = "朋友圈"
            } else { // 非折叠状态
                bind.collapsingToolbar.title = ""
            }

            bind.refreshLayout.isEnabled = verticalOffset >= 0
        })

        bind.recyclerView.layoutManager=LinearLayoutManager(this)
        bind.recyclerView.adapter=adapter

        val retrofit = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("http://thoughtworks-ios.herokuapp.com/")
            .build()

        val api = retrofit.create(API::class.java)

        api.getUser().enqueue(object : Callback<UserBean> {
            override fun onResponse(call: Call<UserBean>, response: Response<UserBean>) {
                bind.userText.text=response.body()?.nick
                Glide.with(this@MainActivity)
                    .load(response.body()?.profileImage)
                    .placeholder(R.drawable.def_bg)
                    .fallback(R.drawable.def_bg)
                    .into(bind.appBarImage)
                Glide.with(this@MainActivity)
                    .load(response.body()?.avatar)
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(20)))
                    .into(bind.userImg)
            }

            override fun onFailure(call: Call<UserBean>, t: Throwable) {
                println("获取数据报错=${t.message}")
            }
        })



        api.getTweetList().enqueue(object : Callback<ArrayList<TweeBean>> {
            override fun onResponse(
                call: Call<ArrayList<TweeBean>>,
                response: Response<ArrayList<TweeBean>>
            ) {
                twees.clear()
                response.body()
                    ?.filterNot { it.content.isNullOrEmpty() && it.images.isNullOrEmpty() }?.let {
                    twees.addAll(
                        it
                    )
                }
                adapter.setList(page(page))
            }

            override fun onFailure(call: Call<ArrayList<TweeBean>>, t: Throwable) {
                println("获取数据报错=${t.message}")
            }

        })
    }

    fun page(page: Int, size: Int = 5): List<TweeBean> {
        return when {
            twees.size < page * size -> emptyList()
            twees.size >= page * size && twees.size <= (page + 1) * size -> twees.subList(
                page * size,
                twees.size
            )
            else -> twees.subList(page * size, (page + 1) * size)
        }
    }

}